package cn.hdu.liang.ch6;


import java.util.*;
import java.util.stream.Collectors;

public class GroupTrans {
    public static List<Transaction> trans = Arrays.asList(
            new Transaction(Currency.EUR, 1500.0),
            new Transaction(Currency.USD, 2300.0),
            new Transaction(Currency.GBP, 9900.0),
            new Transaction(Currency.EUR, 1100.0),
            new Transaction(Currency.JPY, 7800.0),
            new Transaction(Currency.CHF, 6700.0),
            new Transaction(Currency.EUR, 5600.0),
            new Transaction(Currency.USD, 4500.0),
            new Transaction(Currency.CHF, 3400.0),
            new Transaction(Currency.GBP, 3200.0),
            new Transaction(Currency.USD, 4600.0),
            new Transaction(Currency.JPY, 5700.0),
            new Transaction(Currency.EUR, 6800.0));

    public static void main(String[] args) {
        groupImperatively();
        groupFunctionally();
    }

    private static void groupImperatively() {
        Map<Currency, List<Transaction>> transByCu = new HashMap<>();
        for(Transaction tran : trans) {
            Currency cu = tran.getCurrency();
            List<Transaction> transForCu = transByCu.get(cu);
            if(transForCu == null) {
                transForCu = new ArrayList<>();
                transByCu.put(cu, transForCu);
            }
            transForCu.add(tran);
        }
        System.out.println(transByCu);
    }


    private static void groupFunctionally() {
        Map<Currency, List<Transaction>> transByCu = trans.stream()
                .collect(Collectors.groupingBy(Transaction::getCurrency));
        System.out.println(transByCu);
    }
}
